package com.zisuyi.game.sdk.base.net

import com.weilele.mvvm.base.helper.*
import com.zisuyi.game.sdk.base.net.Api
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext


/**
 * 访问网络请求
 */
fun <T, API : Api> CoroutineScope.bindLiveDataWithNetwork(
        api: API,
        data: StatusLiveData<T>? = null,
        context: CoroutineContext = EmptyCoroutineContext,
        start: CoroutineStart = CoroutineStart.DEFAULT,
        resultCall: LiveDataRunnable = DefaultLiveDataRunnable(),
        isToastError: Boolean = true/*是否toast出错误*/,
        isKeepLastValue: Boolean = false/*是否保留之前已经赋值的数据*/,
        errorCall: ((Throwable) -> T?)? = null,
        call: suspend API.() -> T?): Job {
    return this.launch(context, start) {
        resultCall.invoke(data, isToastError, isKeepLastValue, errorCall){
            call.invoke(api)
        }
    }
}

